package com.cloud.neo4j.controller.entity;

import com.cloud.neo4j.business.dto.query.QueryEntity;
import com.cloud.neo4j.business.dto.result.ResultEntity;
import com.cloud.neo4j.business.neo4j.car.entity.business.PersonRelationShipEntity;
import com.cloud.neo4j.common.neo4j.Neo4jRelationShipResponse;
import com.cloud.neo4j.common.neo4j.Neo4jResponse;
import com.cloud.neo4j.common.response.ResponseBean;
import lombok.extern.log4j.Log4j2;
import org.neo4j.driver.Driver;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/**
 * 测试查询
 * @date 20220523
 * @author 刘房
 */
@RestController
@Log4j2
public class EntityExtentionController {

    @Autowired
    private Driver driver;

    /**
     * 实体扩展
     * @param entity    请求参数封装实体
     * @return ResponseBean
     */
    @PostMapping(path ="/entity/extention", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean entityExtention(QueryEntity entity){
        String sql = "MATCH (n1:" + entity.getLabel() + ")<-[r]->(n2) where n1." + entity.getAttribute() + "='" + entity.getValue() + "'RETURN n1,r,n2";
        /**自动关闭资源*/
        try (Session session = driver.session()) {
            Result result = session.run(sql);
            /**处理返回结果*/
            List<ResultEntity> resultEntityList = Neo4jResponse.getResultEntity(result.list());
            return ResponseBean.getResultsSuccess(resultEntityList);
        }catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.getResultsFail("查询失败");
        }
    }

    @PostMapping(path ="/entity/relation/ship", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean entityPersonRelationShip(QueryEntity entity){
        String sql = "MATCH (p:Person{name:\"Tom Hanks\"})-[:ACTED_IN]->(m)<-[:ACTED_IN]-(pw:Person) with p,pw,count(pw) as number where number >1  RETURN pw,p,number";
        /**自动关闭资源*/
        try (Session session = driver.session()) {
            Result result = session.run(sql);
            /**处理返回结果*/
            List<PersonRelationShipEntity> resultEntityList = Neo4jRelationShipResponse.getResultEntity(result.list());
            return ResponseBean.getResultsSuccess(resultEntityList);
        }catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.getResultsFail("查询失败");
        }
    }
}
